<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of search
 *
 * @author Administrator
 */
class search extends CI_Controller {

  //put your code here
  public function __construct() {
    parent::__construct();
    set_userdata('end_user_current_url', current_url());
    if (!userdata('country_id') || !userdata('state_id') || !userdata('city_id')) {
      set_userdata('redirect_view', current_url());
      if (!userdata('end_user_user_id')) {
        redirect('welcome');
      } else {
        redirect('welcome/location');
      }
      return;
    }
  }

  public function index($max = '', $offset = '') {
    if (!empty($_REQUEST['keyword'])) {
      $keyword = $_REQUEST['keyword'];
      $where = "(title like '%$keyword%' or description like '%$keyword%') and (status = " . PROMOTION_PUBLISH
              . ' and start_date <= ' . time() . ' and end_date >= ' . time() . ' and remain > 0)';
      $max = $this->setting_model->item('max_record');
      $offset = $offset + 0;
      $this->db->order_by('date_publish', 'desc');
      $conditions = array();
      if (userdata('country_id'))
        $conditions['country_id'] = userdata('country_id');
      if (userdata('state_id'))
        $conditions['state_id'] = userdata('state_id');
      if (userdata('city_id'))
        $conditions['city_id'] = userdata('city_id');
      $this->db->where($conditions);
      $this->db->order_by('end_date', 'asc');
      $promotions = $this->db->get_where(DB_TABLE_PROMOTION, $where, $max, $offset)->result_array();
      foreach ($promotions as $i => $promotion) {
        $promotions[$i]['medias'] = $this->promotion_media_model->get_all(array('promotion_id' => $promotion['id']));
        $promotions[$i]['num_got'] = $this->promotion_download_model->count(array('promotion_id' => $promotion['id']));
      }
      $this->db->where($where);
      $this->db->where($conditions);
      $total = $this->db->count_all_results(DB_TABLE_PROMOTION);
      $this->load->helper('paging');
      $paging = paging('search/index', $total, $max, $offset, null, '?keyword=' . $keyword);
      $this->load->view('user/search', array(
          'keyword' => $keyword, 'promotions' => $promotions, 'paging' => $paging,
          'title_html' => $this->lang->line('front-end.title.index')));
    } else {
      redirect('index');
    }
  }

}